package com.rui.service.impl;

import com.rui.domain.Student;
import com.rui.domain.StudentExample;
import com.rui.domain.User;
import com.rui.domain.UserExample;
import com.rui.mapper.StudentMapper;
import com.rui.mapper.UserMapper;
import com.rui.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Transactional
@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Student findStudentByStuNo(String stuNo) {
        Student student = studentMapper.selectByPrimaryKey(stuNo);
        return student;
    }

    @Override
    public boolean saveStudentAndUser(Student student, User user) {
        //先保存学生信息
        int rows1 = studentMapper.insert(student);
        //再保存用户信息
        int rows2 = userMapper.insert(user);
        if (rows1 > 0 && rows2 > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<Student> findStudentsByJobNo(String jobNo, int year) {
        StudentExample example = new StudentExample();
        StudentExample.Criteria criteria = example.createCriteria();
        criteria.andTeacherIdEqualTo(jobNo);
        criteria.andGradeEqualTo(String.valueOf(year));
        return studentMapper.selectByExample(example);
    }

    @Override
    public boolean updateStudent(Student student) {
        int rows = studentMapper.updateByPrimaryKeySelective(student);
        if (rows > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteStudent(String stuNo) {
        int rows1 = studentMapper.deleteByPrimaryKey(stuNo);
        //int i=1/0;
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(stuNo);
        int rows2 = userMapper.deleteByExample(example);
        if (rows1>0 && rows2>0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteBatchStudents(String[] stuNo) {
        List<String> list = Arrays.asList(stuNo);
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        criteria.andStuNoIn(list);
        int rows1 = studentMapper.deleteByExample(studentExample);
//        int i=1/0;
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria1 = userExample.createCriteria();
        criteria1.andUsernameIn(list);
        int rows2 = userMapper.deleteByExample(userExample);
        if (rows1>0 && rows2> 0) {
            return true;
        }
        return false;
    }
}
